<template>
  <div class="p-[10px]">
    <n-card title="数据看板" size="huge" hoverable>
      <!-- 搜索 -->
      <n-form inline :label-width="80" :model="formValue">
        <n-form-item label="起止时间" path="datetimerange">
          <n-date-picker v-model:value="formValue.datetimerange" type="daterange" clearable />
        </n-form-item>
        <n-form-item label="时间粒度" path="model_name">
          <n-select style="width:100px" v-model:value="formValue.value" :options="options" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" @click="getLog"> 查询 </n-button>
        </n-form-item>
      </n-form>
      <n-row class="!mb-2">
        <n-col :span="2">
          <n-statistic label="总消耗额度">￥{{ (userinfos.quota / 500000).toFixed(2) }}</n-statistic>
        </n-col>
        <n-col :span="2">
          <n-statistic label="历史消耗"> ￥{{ (userinfos.used_quota / 500000).toFixed(2) }} </n-statistic>
        </n-col>
        <n-col :span="2">
          <n-statistic label="请求次数"> {{ userinfos.request_count }} </n-statistic>
        </n-col>
        <n-col :span="2">
        </n-col>
        <n-col :span="2">
          <n-statistic label="统计额度"> ￥{{( toolsBarViews.totalQuota/500000).toFixed(2) }} </n-statistic>
        </n-col>
        <n-col :span="2">
          <n-statistic label="统计Tokens"> {{ toolsBarViews.totalTokens }} </n-statistic>
        </n-col>
        <n-col :span="2">
          <n-statistic label="统计次数">{{ toolsBarViews.totalTimes }}</n-statistic>
        </n-col>
        <n-col :span="2">
        </n-col>
        <n-col :span="2">
          <n-statistic label="平均RPM"> {{ toolsBarViews.RPM }} </n-statistic>
        </n-col>
        <n-col :span="2">
          <n-statistic label="平均TPM"> {{ toolsBarViews.TPM }} </n-statistic>
        </n-col>
      </n-row>
      <n-tabs @update:value="syncBarPosition" type="line" display-directive="if" animated>
        <n-tab-pane name="a" tab="消耗分布">
          <div id="maina" style="height:500px;width:100%"></div>
        </n-tab-pane>
        <n-tab-pane name="b" tab="调用次数分布">
          <div id="mainb" style="height:500px;width:100%"></div>
        </n-tab-pane>
      </n-tabs>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { defineProps, h, ref, onMounted } from "vue";
import * as echarts from 'echarts';
import { formatDateTime, getOpction } from "./utils.js"
import {
  NDataTable,
  NTag,
  NRow,
  NCol,
  NStatistic,
  NCard,
  NFormItem,
  NForm,
  NInput,
  NButton,
  NDatePicker,
  NSelect,
  NTabs,
  NTabPane
} from "naive-ui";
import { fetchLog, fetchLogStat, fetchSelf, fetchRequestData } from "@/api/index";
import dayjs from "dayjs";
// 获取今天的日期\
const today = dayjs();

// // 获取昨天的日期
const yesterdayAtMidnight = today.subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss');
const props = defineProps();
const formValue = ref({
  token_name: "",
  model_name: "",
  datetimerange: [new Date(yesterdayAtMidnight), new Date()],
  p: 1,
  value: "hour",
  page_size: 99999,
});

const data = ref([]);
const stat = ref({});
const userinfos = ref({});
const toolsBarViews = ref({
  // 统计额度
  totalQuota: 0,
  totalTokens: 0,
  totalTimes: 0,
  RPM:0,
  TPM:0
});
const activeData = ref("a")
const options = ref([
  {
    label: '小时',
    value: 'hour',
  },
  {
    label: '天',
    value: 'day'
  },
  {
    label: '周',
    value: 'week'
  }
])
function syncBarPosition(t) {
  activeData.value = t;
  getLog(activeData.value);
}
const getLog = async (t) => {
  const params = {
    start_timestamp: ((new Date(formValue.value.datetimerange[0])).getTime() / 1000).toFixed(0),
    end_timestamp: ((new Date(formValue.value.datetimerange[1])).getTime() / 1000).toFixed(0),
    default_time: formValue.value.value
  };
  const userdelf = await fetchSelf();
  userinfos.value = userdelf.data
  let repobndata = await fetchRequestData(params)
  toolsBarViews.value = {
     totalQuota: 0,
    totalTokens: 0,
    totalTimes: 0,
    RPM:0,
    TPM:0
  }

  sendeData1(repobndata, activeData.value)
};
var emphasisStyle = {
  itemStyle: {
    shadowBlur: 10,
    shadowColor: 'rgba(0,0,0,0.3)'
  }
};
var myChart = {};
function renderCanvass1(series, xAxisData, types) {
  console.log(document.getElementById('main' + types))
  if (myChart['main' + types]) {
    myChart['main' + types].dispose(); // 销毁实例
  }
  myChart['main' + types] = echarts.init(document.getElementById('main' + types));
  var option = getOpction(types, series, xAxisData);
  myChart['main' + types].on('brushSelected', function (params) {
    var brushed = [];
    var brushComponent = params.batch[0];
    for (var sIdx = 0; sIdx < brushComponent.selected.length; sIdx++) {
      var rawIndices = brushComponent.selected[sIdx].dataIndex;
      brushed.push('[Series ' + sIdx + '] ' + rawIndices.join(', '));
    }
  });
  option && myChart['main' + types].setOption(option);
}
function sendeData1(reponeData, type) {
  let tmpe = {};
  let tlength = 0;
  let arrsts = [];
  let reanderCanvs = {};
  for (let pop of reponeData.data) {
    if (!tmpe[pop.created_at]) {
      tmpe[pop.created_at] = []
    }
    tmpe[pop.created_at].push(pop);
    if (tlength < tmpe[pop.created_at].length) {
      tlength = tmpe[pop.created_at].length
      arrsts = tmpe[pop.created_at].map(e => {
        return {
          name: e.model_name,
          type: 'bar',
          stack: 'one',
          emphasis: emphasisStyle,
          data: []
        }
      })
    }
  }
  let t = Object.keys(tmpe).sort((a, b) => a + b);
  for (let pop of t) {
    for (let services of arrsts) {
      services.data.push(0);
    }
    for (let s of tmpe[pop]) {
      if (!reanderCanvs[s.model_name]) {
        reanderCanvs[s.model_name] = 0
      }
      reanderCanvs[s.model_name] += s.count
      toolsBarViews.value.totalQuota += s.quota
      toolsBarViews.value.totalTokens += s.token_used;
      toolsBarViews.value.totalTimes += s.count;
      for (let services of arrsts) {
        if (s.model_name == services.name) {
          services.data[services.data.length - 1] = (s.token_used / 50000).toFixed(4);
        }
      }
    }
  }
  t = t.map(e => formatDateTime(new Date(e * 1000), "MM-dd hh:ss"));
  console.log(toolsBarViews.value.totalTimes);

 toolsBarViews.value.RPM= (toolsBarViews.value.totalTimes  /
 ((Date.parse(new Date(formValue.value.datetimerange[1]))-Date.parse(new Date(formValue.value.datetimerange[0])))/ 60000)).toFixed(3)

 toolsBarViews.value.TPM= (toolsBarViews.value.totalTokens  /
 ((Date.parse(new Date(formValue.value.datetimerange[1]))-Date.parse(new Date(formValue.value.datetimerange[0])))/ 60000)).toFixed(3)

  if (type == 'a') {
    renderCanvass1(arrsts, t, type)
  } else {
    let obj = [];
    Object.keys(reanderCanvs).map(e => {
      obj.push({
        name: e,
        value: reanderCanvs[e]
      })
    })
    renderCanvass1(obj, t, type)
  }
}
onMounted(() => {
  getLog('a');
  //   console.log(tmpe)
});
</script>
